# templates/controller.py.j2
from fastapi import APIRouter, Depends
from fastapi_utils.cbv import cbv
from sqlalchemy.ext.asyncio import AsyncSession
from src.utils.auth.auth import AllUserAuth, PermissionAuth
from src.db.db_database import alchemy
from src.core.base_controller import BaseController
from src.core.dependencies import IdList
from src.core.response.response_schema import (
    ResponseGenericSchema,
    ResponseSchema,
    PageResponseDataSchema,
)
from src.schemas.code_generator_schema import (
    CodegeneratorParams,
    CodegeneratorOut,
    CodegeneratorUpdate,
    CodegeneratorCreate,
)
from src.services.code_generator_service import CodegeneratorService

router = APIRouter()


@cbv(router)
class PostController(BaseController):
    db: AsyncSession = Depends(alchemy.provide_session())
    code_generator_service: CodegeneratorService = Depends(
        alchemy.provide_service(CodegeneratorService)
    )

    @router.get(
        "/list",
        summary="列表",
        tags=["代码生成管理"],
        response_model=ResponseGenericSchema[PageResponseDataSchema[CodegeneratorOut]],
        dependencies=[Depends(AllUserAuth())],
    )
    async def get_post_list(self, param: CodegeneratorParams = Depends()):
        where = await param.get_where_and_limit_offset(self.db)
        res, count = await self.code_generator_service.list_and_count(*where)
        return self.paginated_response(
            data=res, total=count, current=param.page, size=param.limit
        )

    @router.post(
        "/add",
        summary="创建",
        description="创建",
        tags=["代码生成管理"],
        dependencies=[Depends(PermissionAuth(["{{ permissions }}:add"]))],
        response_model=ResponseSchema,
    )
    async def add_code_generator(
        self,
        model: CodegeneratorCreate,
    ):
        await self.code_generator_service.create(model, auto_commit=True)
        return self.success(message="创建成功")

    @router.put(
        "/update",
        summary="修改",
        description="修改",
        tags=["代码生成管理"],
        dependencies=[Depends(PermissionAuth(["{{ permissions }}:update"]))],
        response_model=ResponseSchema,
    )
    async def update_code_generator(
        self,
        model: CodegeneratorUpdate,
    ):
        await self.code_generator_service.update(model, auto_commit=True)
        return self.success(message="更新成功")

    @router.delete(
        "/delete",
        summary="删除",
        description="删除",
        tags=["代码生成管理"],
        dependencies=[Depends(PermissionAuth(["{{ permissions }}:delete"]))],
        response_model=ResponseSchema,
    )
    async def delete_code_generator(
        self,
        ids: IdList = Depends(),
    ):
        await self.code_generator_service.delete_many(ids.ids, auto_commit=True)
        return self.success(message="删除成功")
